<template>
  <div class="appointments-page">
    <el-container>
      <el-header class="page-header">
        <h2>我的预约</h2>
       
      </el-header>
      
      <el-main>
        <el-card class="filter-card" shadow="never">
          <el-form :model="filters" inline>
            <el-form-item label="预约状态">
              <el-select v-model="filters.status" placeholder="全部状态" clearable @change="fetchList">
                <el-option label="全部" value="" />
                <el-option label="待确认" value="pending" />
                <el-option label="已确认" value="confirmed" />
                <el-option label="已取消" value="cancelled" />
                <el-option label="已完成" value="completed" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button @click="resetFilters">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <el-card class="list-card" shadow="never">
          <div v-if="loading" class="loading-container">
            <el-skeleton :rows="3" animated />
          </div>

          <div v-else-if="list.length === 0" class="empty-container">
            <el-empty description="暂无预约记录">
              <el-button type="primary" @click="$router.push('/properties')">
                浏览房源
              </el-button>
            </el-empty>
          </div>

          <div v-else class="appointments-list">
            <div class="appointment-item" v-for="item in list" :key="item.id">
              <div class="appointment-image">
                <img :src="getCoverImage(item.property_images)" :alt="item.property_title" />
                <div class="status-badge" :class="getStatusClass(item.status)">
                  {{ getStatusText(item.status) }}
                </div>
              </div>
              
              <div class="appointment-info">
                <div class="appointment-header">
                  <h3 class="property-title">{{ item.property_title }}</h3>
                  <div class="property-price">
                    <span class="price">￥{{ item.property_price }}</span>
                    <span class="unit">/月</span>
                  </div>
                </div>
                
                <div class="appointment-meta">
                  <div class="meta-item">
                    <el-icon><Location /></el-icon>
                    <span>{{ item.property_address }}</span>
                  </div>
                  <div class="meta-item">
                    <el-icon><Calendar /></el-icon>
                    <span>{{ formatDateTime(item.appointment_date) }}</span>
                  </div>
                  <div class="meta-item">
                    <el-icon><Phone /></el-icon>
                    <span>{{ item.contact_phone }}</span>
                  </div>
                </div>
                
                <div class="appointment-details">
                  <div class="detail-item">
                    <strong>联系人：</strong>{{ item.contact_name || '未填写' }}
                  </div>
                  <div class="detail-item" v-if="item.remark">
                    <strong>备注：</strong>{{ item.remark }}
                  </div>
                  <div class="detail-item">
                    <strong>房东：</strong>{{ item.owner_name || '未知' }}
                  </div>
                </div>
                
                <div class="appointment-footer">
                  <div class="appointment-time">
                    <el-icon><Clock /></el-icon>
                    <span>预约于 {{ formatDate(item.created_at) }}</span>
                  </div>
                  <div class="appointment-actions">
                    <el-button size="small" @click="viewProperty(item.property_id)">查看房源</el-button>
                    <el-button 
                      size="small" 
                      type="danger" 
                      @click="cancelAppointment(item)"
                      v-if="item.status === 'pending' || item.status === 'confirmed'"
                    >
                      取消预约
                    </el-button>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="pagination" v-if="total > 0">
            <el-pagination
              v-model:current-page="page"
              :page-size="pageSize"
              :total="total"
              layout="total, prev, pager, next"
              @current-change="fetchList"
            />
          </div>
        </el-card>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { appointmentsAPI } from '@/api/appointments'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()
const loading = ref(false)
const list = ref([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(10)

const filters = reactive({
  status: ''
})

const getCoverImage = (images) => {
  if (images && images.length > 0) {
    return images[0]
  }
  return 'https://picsum.photos/seed/house/300/200'
}

const getStatusText = (status) => {
  const statusMap = {
    pending: '待确认',
    confirmed: '已确认',
    cancelled: '已取消',
    completed: '已完成'
  }
  return statusMap[status] || '未知'
}

const getStatusClass = (status) => {
  const classMap = {
    pending: 'status-pending',
    confirmed: 'status-confirmed',
    cancelled: 'status-cancelled',
    completed: 'status-completed'
  }
  return classMap[status] || 'status-pending'
}

const formatDate = (date) => {
  return new Date(date).toLocaleDateString('zh-CN')
}

const formatDateTime = (date) => {
  return new Date(date).toLocaleString('zh-CN')
}

const fetchList = async () => {
  try {
    loading.value = true
    const params = {
      page: page.value,
      pageSize: pageSize.value,
      ...filters
    }
    
    const res = await appointmentsAPI.getUserAppointments(params)
    if (res?.success) {
      list.value = res.data.items
      total.value = res.data.total
    }
  } catch (error) {
    console.error('获取预约列表失败:', error)
    ElMessage.error('获取预约列表失败')
  } finally {
    loading.value = false
  }
}

const resetFilters = () => {
  filters.status = ''
  page.value = 1
  fetchList()
}

const viewProperty = (propertyId) => {
  router.push(`/properties/${propertyId}`)
}

const cancelAppointment = async (appointment) => {
  try {
    await ElMessageBox.confirm(
      `确定要取消预约"${appointment.property_title}"吗？`,
      '确认取消',
      {
        confirmButtonText: '确定取消',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    const res = await appointmentsAPI.cancel(appointment.id)
    if (res?.success) {
      ElMessage.success('预约已取消')
      fetchList()
    } else {
      ElMessage.error(res?.message || '取消失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消预约失败:', error)
      ElMessage.error('取消失败，请重试')
    }
  }
}

onMounted(() => {
  fetchList()
})
</script>

<style scoped>
.appointments-page {
  min-height: 100vh;
  background: #f6f8fb;
}

.page-header {
  background: #fff;
  border-bottom: 1px solid #e8e8e8;
  padding: 24px;
  text-align: center;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #333;
}

.page-header p {
  margin: 0;
  color: #666;
}

.filter-card {
  margin-bottom: 16px;
}

.list-card {
  min-height: 400px;
}

.loading-container {
  padding: 20px;
}

.empty-container {
  padding: 40px 20px;
}

.appointments-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.appointment-item {
  display: flex;
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  transition: all 0.3s;
}

.appointment-item:hover {
  box-shadow: 0 4px 16px rgba(0,0,0,0.15);
  transform: translateY(-2px);
}

.appointment-image {
  position: relative;
  width: 200px;
  height: 150px;
  flex-shrink: 0;
}

.appointment-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.status-badge {
  position: absolute;
  top: 8px;
  right: 8px;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  color: #fff;
}

.status-pending {
  background: #faad14;
}

.status-confirmed {
  background: #52c41a;
}

.status-cancelled {
  background: #ff4d4f;
}

.status-completed {
  background: #1890ff;
}

.appointment-info {
  flex: 1;
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.appointment-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 8px;
}

.property-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
  flex: 1;
}

.property-price {
  text-align: right;
}

.price {
  font-size: 20px;
  font-weight: bold;
  color: #ff4d4f;
}

.unit {
  font-size: 14px;
  color: #8c8c8c;
  margin-left: 4px;
}

.appointment-meta {
  display: flex;
  gap: 16px;
  margin-bottom: 8px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #666;
  font-size: 14px;
}

.appointment-details {
  flex: 1;
  margin-bottom: 8px;
}

.detail-item {
  margin-bottom: 4px;
  color: #666;
  font-size: 14px;
}

.appointment-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 8px;
  border-top: 1px solid #f0f0f0;
}

.appointment-time {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #8c8c8c;
  font-size: 12px;
}

.appointment-actions {
  display: flex;
  gap: 8px;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}
</style>
